<template>
  <div>

    <n-space style="margin-bottom: 10px" justify="space-between">
      <n-space>
        <n-select style="width: 300px" :options = keyWordPlanOptions  v-model:value="extractOption">

        </n-select>
        <n-popconfirm
            @positive-click="getPromptList"
        >
          <template #trigger>
            <n-button type="primary">全部推理</n-button>
          </template>
          全部推理将所有分镜重新推理,包含已经推理出关键词的分镜
        </n-popconfirm>

<!--        <n-popconfirm-->
<!--            @positive-click="translateList"-->
<!--        >-->
<!--          <template #trigger>-->
<!--            <n-button type="primary">全部翻译</n-button>-->
<!--          </template>-->
<!--          全部翻译将所有关键词进行翻译-->
<!--        </n-popconfirm>-->
      </n-space>

<!--      <n-upload-->
<!--          :multiple="false"-->
<!--          @change="changeFile"-->
<!--      >-->
<!--        <n-button type="primary">选择文件</n-button>-->
<!--      </n-upload>-->

    </n-space>
    <n-data-table
            :single-line="false"
            :columns="createColumns"
            :data="boardList"
            :loading="tableLoading"
            :style="{ height: `${clientHeight - 165}px` }"
            flex-height
    />
      <n-modal
          v-model:show="progressModal"
          class="custom-card"
          style="width: 500px"
          preset="card"
          title="任务进度"
          size="huge"
          :bordered="false"
      >
          <n-space justify="space-around">
              <n-statistic label="当前进度" :value="currentTaskNum">
                  <template #prefix>
                  </template>
                  <template #suffix>
                      / {{boardList.length}}
                  </template>
              </n-statistic>

              <n-statistic label="成功/失败" >
                  <template #prefix>
                      {{taskStatus.successNum}}
                  </template>
                  <template #suffix>
                      / {{taskStatus.failNum}}
                  </template>
              </n-statistic>
          </n-space>
          <n-progress
              type="line"
              :percentage = " Math.round(currentTaskNum/boardList.length*100) "
              :height="30"
              :border-radius="5"
              :fill-border-radius="0"
          />
      </n-modal>
      <n-modal
          v-model:show="addModalShow"
          style="width: 600px"
          preset="card"
          title="新增分镜"
          size="huge"
          :bordered="false"
      >
        <n-form>
          <n-h4>您当前在第<n-tag type="primary">{{addNum}}</n-tag>分镜插入分镜,新增分镜编号为:<n-tag type="primary">{{addNum+1}}</n-tag></n-h4>
          <n-form-item label="原文描述">
            <n-input type="textarea" style="height: 100px;" v-model:value="editDataForm.content"></n-input>
          </n-form-item>
          <n-form-item label="画面关键词">
            <n-input type="textarea" style="height: 100px;" v-model:value="editDataForm.prompt"></n-input>
          </n-form-item>
          <n-form-item label="关键词翻译">
            <n-input type="textarea" style="height: 100px;" v-model:value="editDataForm.promptEn"></n-input>
          </n-form-item>
        </n-form>
        <template #footer>
          <n-space justify="end">
            <n-button @click="addModalShow=false">取消</n-button>
            <n-button type="primary" @click="addOrUpdateBoard">确认</n-button>
          </n-space>
        </template>
      </n-modal>

      <n-modal
        v-model:show="updateModalShow"
        style="width: 800px"
        preset="card"
        title="分镜编辑"
        size="huge"
        :bordered="false"
      >
        <n-form>
          <n-row>
            <n-col span="11">
                <n-form-item label="原文描述">
                  <n-input type="textarea" disabled style="height: 100px;" v-model:value="editDataFrom_refer.content"></n-input>
                </n-form-item>
            </n-col>
            <n-col span="2">
                <n-space justify="center" style="margin-top: 50px">
                  <n-icon :component="ArrowForwardOutline" size="30"></n-icon>
                </n-space>
            </n-col>
            <n-col span="11">
              <n-form-item label="原文描述">
                <n-input type="textarea" style="height: 100px;" v-model:value="editDataForm.content"></n-input>
              </n-form-item>
            </n-col>
          </n-row>
          <n-row>
            <n-col span="11">
              <n-form-item label="画面关键词">
                <n-input type="textarea" disabled style="height: 100px;" v-model:value="editDataFrom_refer.prompt"></n-input>
              </n-form-item>
            </n-col>
            <n-col span="2">
              <n-space justify="center" style="margin-top: 50px">
                <n-icon :component="ArrowForwardOutline" size="30"></n-icon>
              </n-space>
            </n-col>
            <n-col span="11">
              <n-form-item label="画面关键词">
                <n-input type="textarea" style="height: 100px;" v-model:value="editDataForm.prompt"></n-input>
              </n-form-item>
            </n-col>
          </n-row>
          <n-row>
            <n-col span="11">
              <n-form-item label="关键词翻译">
                <n-input type="textarea" disabled style="height: 100px;" v-model:value="editDataFrom_refer.promptEn"></n-input>
              </n-form-item>
            </n-col>
            <n-col span="2">
              <n-space justify="center" style="margin-top: 50px">
                <n-icon :component="ArrowForwardOutline" size="30"></n-icon>
              </n-space>
            </n-col>
            <n-col span="11">
              <n-form-item label="关键词翻译">
                <n-input type="textarea" style="height: 100px;" v-model:value="editDataForm.promptEn"></n-input>
              </n-form-item>
            </n-col>
          </n-row>
        </n-form>
          <template #footer>
              <n-space justify="end">
                  <n-button @click="updateModalShow=false">取消</n-button>
                  <n-button type="primary" @click="addOrUpdateBoard">确认</n-button>
              </n-space>
          </template>
      </n-modal>
  </div>
</template>
<script setup lang="ts">
import {NButton, NInput, NSelect, NTag, NTreeSelect, TreeOption, useMessage} from 'naive-ui'
import {defineComponent, h, nextTick, onMounted, reactive, ref} from "vue";
import {storyController} from "@/api/story/story.api";
import {storyCharacterController} from '@/api/controller/story/storyCharacterController'
import {storyBoardController} from "@/api/controller/story/storyBoard.api";
import { ArrowForwardOutline } from '@vicons/ionicons5'
import {tagCategoryController} from '@/api/controller/tagcategory/tagCategoryController'
import {storeToRefs} from "pinia";
import {useSystemStore} from "@/store/modules/useSystemStore";


const message = useMessage()
const story = ref("")
const progressModal = ref(false)
const extractOption = ref("V2")
const tableLoading = ref(false)
const addOrUpdateLoading = ref(false)
const updateModalShow = ref(false)
const addModalShow = ref(false)
const addNum = ref(0)

const {
  clientHeight,
  layoutHeaderHeight,
  darkTheme,
  tabsHeight
} = storeToRefs(useSystemStore());

const editDataFrom_refer = reactive({
  content: "",
  prompt: "",
  promptEn: ""
})

const editDataForm = reactive({
  id:"",
  chapterId:"",
  content: "",
  prompt: "",
  promptEn: "",
  orderNum: -1,
  characterName: ""
})


// 分镜列表
const boardList = ref([])

const storyCharacterOption = ref([])

// 当前推理的分镜
const currentTaskNum = ref(1)
// 任务状态
const taskStatus = ref({
    successNum : 0,
    failNum : 0
})

let cameraOption =  []
let angleOption = []
let backgroundOption = []


const props = defineProps({
  storyId: {
    type: String,
    required: true
  }
})

// 列表字段
const createColumns = [
  {
    title: '操作',
    width: 100,
    render (row) {
      return [h(
          NButton,
          {
            size: 'small',
            block: true,
            type: 'warning',
            onClick: () => deleteBoard(row)
          },
          { default: () => '删除',type:"error" }
      ), h(
          NButton,
          {
            size: 'small',
            block: true,
            type: 'info',
            style: 'margin-top:5px;',
            onClick: () => addBoard(row)
          },
          { default: () => '插入' }
      ),
      //   h(
      //     NButton,
      //     {
      //       size: 'small',
      //       block: true,
      //       type: 'info',
      //       style: 'margin-top:5px;',
      //       onClick: () => editBoard(row)
      //     },
      //     { default: () => '编辑' }
      // ),
        h(
          NButton,
          {
            size: 'small',
            block: true,
            type: 'primary',
            onClick: () => getPrompt(row),
            loading: row.loading,
            style: 'margin-top:5px;'
          },
          { default: () => '推理' }
      )
      //   , h(
      //     NButton,
      //     {
      //       size: 'small',
      //       block: true,
      //       type: 'primary',
      //       onClick: () => translateRow(row),
      //       loading: row.translateLoading,
      //       style: 'margin-top:5px;'
      //     },
      //     { default: () => '翻译' }
      // )
      //
      ]
    }
  },
  {
    title: '#',
    key: 'orderNum',
    width: 40
  },
  {
    title: '原文描述',
    key: 'content',
    width: 300,
    render(row, index) {
      return h(NInput, {
        value: row.content,
        type: 'textarea',
        style: 'height: 100px',
        onBlur () {
          updateBoard(boardList.value[index])
        },
        onUpdateValue(v) {
          boardList.value[index].content = v
        }
      })
    }
  },
  {
    title: '画面关键字',
    key: 'prompt',
    width:300,
    render(row, index){
      return h(NInput, {
        value: row.prompt,
        type: 'textarea',
        style: 'height: 100px',
        onBlur () {
          if(boardList.value[index]?.isChange) {
            updateBoard(boardList.value[index])
          }
        },
        onUpdateValue(v){
          if( v != boardList.value[index].prompt) {
            boardList.value[index].prompt = v
            boardList.value[index].isChange = true
          }
        }
      })
    }
  }, {
    title: '详细设置',
    key: 'prompt',
    width: 200,
    render (row, index) {
      const details = row.details
      return h(Detail, {
          angle: row.angle,
          camera: row.camera,
          background: row.background,
          index: index
      })
    }
  },{
        title: '人物',
        key: 'character',
        width: 300,
        render(row){
            let selectName ;
            if(row.characterName != null && row.characterName.length > 0){
               selectName = row.characterName.split(",")
            }
            return h(NSelect,{
                options: storyCharacterOption.value,
                labelField: "characterName",
                valueField: "characterName",
                childrenField: "children",
                multiple: true,
                value: selectName,
                renderTag: renderTag,
                onUpdateValue: (v) => {
                    const index = getDataIndex(row.orderNum)
                    boardList.value[index].characterName = v.join(",")
                    updateCharacter(boardList.value[index])
                }
            })
        }
    }
]

const getDataIndex = (orderNum:any) => {
    return boardList.value.findIndex((item) => item?.orderNum === orderNum)
}

// const getTagAttribute = () => {
//   const categoryId = "030103,030107,0307"
//   tagCategoryController.listTagTreeByCategoryId(categoryId).then(res => {
//     if(res.code === 200){
//       angleOption.push({
//         en: res.data['030103'].id,
//         zh: res.data['030103'].categoryName,
//         children: res.data['030103'].attributes,
//         disabled: true
//       })
//       cameraOption.push({
//         en: res.data['030107'].id,
//         zh: res.data['030107'].categoryName,
//         children: res.data['030107'].attributes,
//         disabled: true
//       })
//       res.data['0307'].children.forEach(item => {
//         backgroundOption.push({
//           en: item.id,
//           zh: item.categoryName,
//           children: item.attributes,
//           disabled: true
//         })
//       })
//       getStoryBoardByChapterId()
//     }
//   })
// }

/**
 * 删除分镜
 * @param row
 */
const deleteBoard = (row:any) =>{
  window.$dialog.warning({
    title: "温馨提醒",
    content: "是否继续删除第("+ row.orderNum +")号分镜信息？",
    positiveText: "确定",
    negativeText: "取消",
    onPositiveClick: () => {
      storyBoardController.deleteBoard(row.id,row.chapterId).then(res => {
        if(res.code === 200){
          message.success(res.msg)
          getStoryBoardByChapterId()
        }else {
          message.error(res.msg)
        }
      })
    }
  })
}

const updateCharacter = (row:any) =>{
  storyBoardController.addOrUpdateBoard(row).then(res => {
    if(res.code === 200){
      message.success(res.msg)
    }else {
      message.error(res.msg)
    }
  })
}

const updateBoard =(row:any)=>{
  storyBoardController.addOrUpdateBoard(row).then(res => {
    if(res.code !== 200){
      message.error(res.msg)
    }
  })
}

const addOrUpdateBoard =()=>{
  addOrUpdateLoading.value = true
  storyBoardController.addOrUpdateBoard(editDataForm).then(res => {
    addOrUpdateLoading.value = false
    if(res.code === 200){
      message.success(res.msg)
      getStoryBoardByChapterId()
      addModalShow.value = false
      updateModalShow.value = false
    }else {
      message.error(res.msg)
    }
  })
}

const addBoard = (row:any) =>{
  Object.keys(editDataForm).forEach(key => {
    editDataForm[key] = ''
  })
  addNum.value = row.orderNum
  editDataForm.orderNum = row.orderNum+1
  editDataForm.chapterId = props.storyId
  addModalShow.value = true
}

const editBoard = (row:any) => {
  editDataFrom_refer.content = row.content
  editDataFrom_refer.prompt = row.prompt
  editDataFrom_refer.promptEn = row.promptEn
  editDataForm.content = row.content
  editDataForm.prompt = row.prompt
  editDataForm.promptEn = row.promptEn
  editDataForm.id = row.id
  editDataForm.chapterId = row.chapterId
  editDataForm.characterName = row.characterName
  updateModalShow.value = true
}

const changeFile = async(file:any) => {
  console.log(file, '文件上传');
  if (file.event) {
    // 文件上传
    let formdata = new FormData();
    formdata.append('file', file.file.file);
    formdata.append('chapterId', props.story.id);
    console.log(formdata.get('files'));
    storyController.importStoryBoardByTxt(formdata).then(res => {
      console.log(res);
      if(res.code === 200){
        getStoryBoardByChapterId()
      }else {
        message.error(res.msg)
      }
    })
    // let res = await fileUpload(formdata, config);
    // if (res && res.code === 0) {
    //   if (res.list.length > 0) {
    //     let datas = res.list[0];
    //     props.saveFileArr.push(datas);
    //   }
    // } else {
    //   allData.fileList = [];
    //   let param = {
    //     id: file.file.id,
    //     name: file.file.name,
    //     status: 'error',
    //   };
    //   allData.fileList.push(param);
    // }
  } else {
    // 文件删除,根据文件名进行匹配
    let fileIndex = null;
    // props.saveFileArr.map((item, index) => {
    //   if (file.file.name == item.fileOriginalName) {
    //     fileIndex = index;
    //   }
    // });
    // let fileNos = [];
    // fileNos.push(props.saveFileArr[fileIndex].fileNo);
    // let res = await fileDelete(fileNos);
    // if (res && res.code === 200) {
    //   props.saveFileArr.splice(fileIndex, 1);
    // }
  }
}

const getStoryBoardByChapterId = () =>{
  tableLoading.value = true
  try {
    storyController.getStoryBoardByChapterId(props.storyId).then(res => {
      if (res.code === 200) {
        boardList.value = res.data
      } else {
        message.error(res.msg)
      }
    })
  }catch (e){
    message.error(e)
  }finally {
    tableLoading.value = false
  }
}
//
// const getCharacterOption = () =>{
//   storyCharacterController.getCharacterList(props.storyId).then(res =>{
//     if(res.code === 200){
//       const storyCharacter = {
//         type: 'group',
//         characterName: '人物库中人物',
//         key: 'Let It Be Album',
//         children: res.data
//       }
//       storyCharacterOption.value.push(storyCharacter)
//       console.log('------------------',storyCharacter)
//       getTagAttribute()
//     }
//   })
// }


const getPromptList = async () => {
    currentTaskNum.value = 0
    taskStatus.value = {
        successNum: 0,
        failNum: 0
    }
    progressModal.value = true
    for (const item of boardList.value) {
        currentTaskNum.value ++
        try {
            const res = await storyController.getImageDescription(item, extractOption.value)
            if (res.code === 200) {
                // 成功
                taskStatus.value.successNum++
            } else {
                // 失败
                taskStatus.value.failNum++
            }
        }catch (e) {
            taskStatus.value.failNum++
        }
    }
    getStoryBoardByChapterId()
}


const translateRow = (row:any) =>{
  row.translateLoading = true
  storyBoardController.transToEnglish(row).then(res => {
    row.translateLoading = false
    if(res.code === 200){
      const index = getDataIndex(row.orderNum)
      boardList.value[index].promptEn = res.data
    }else {
      message.error(res.msg)
    }
  })
}

const translateList = async () => {
    currentTaskNum.value = 0
    taskStatus.value = {
        successNum: 0,
        failNum: 0
    }
    progressModal.value = true
    for (const item of boardList.value) {
        currentTaskNum.value ++
        try {
            const res = await storyBoardController.transToEnglish(item)
            if (res.code === 200) {
                // 成功
                taskStatus.value.successNum++
            } else {
                // 失败
                taskStatus.value.failNum++
            }
        }catch (e) {
            taskStatus.value.failNum++
        }
    }
    getStoryBoardByChapterId()
}

const getPrompt = (row:any) => {
    row.loading = true
    storyController.getImageDescription(row,extractOption.value).then(res => {
        row.loading = false
      if(res.code === 200){
          const index = getDataIndex(row.orderNum)
          boardList.value[index].prompt = res.data.prompt
          boardList.value[index].characterName = res.data.characterName
          console.log(boardList.value[index])
      }else {
        message.error(res.msg)
      }
    })
}


onMounted(() => {
  // getCharacterOption()
})


const Detail = defineComponent({
    props: {
        angle: {
            type: String,
            required: true
        },
        camera: {
            type: String,
            required: true
        },
        background: {
            type: String,
            required: true
        },
        index:{
          type: Number,
          required: true
        }
    },
    setup (props) {
        return () =>[
         h(NTreeSelect, {
            options: angleOption ,
            placeholder: '请选择视角',
            size: 'small',
            style: 'width: 200px;margin-top:5px;',
            keyField: 'en',
            labelField: 'zh',
            defaultExpandAll: true,
            value: props.angle,
            clearable: true,
            onUpdateValue: (v) => {
              boardList.value[props.index].angle = v
              updateBoard(boardList.value[props.index])
            }
          }),
          h(NTreeSelect, {
            options: cameraOption,
            placeholder: '请选择镜头',
            size: 'small',
            keyField: 'en',
            labelField: 'zh',
            style: 'width: 200px;margin-top:5px;',
            defaultExpandAll: true,
            clearable: true,
            value: props.camera,
            onUpdateValue: (v) => {
              boardList.value[props.index].camera = v
              updateBoard(boardList.value[props.index])
            }
          }),
          h(NTreeSelect,
    {
            options:  backgroundOption,
            placeholder: '请选择场景',
            size: 'small',
            keyField: 'en',
            labelField: 'zh',
            defaultExpandAll: true,
            clearable: true,
            style: 'width: 200px;margin-top:5px;',
            value: props.background,
            onUpdateValue: (v) => {
              if(v != boardList.value[props.index].background){
                boardList.value[props.index].background = v
                updateBoard(boardList.value[props.index])
              }
            }
          })
        ]
    }
})

const renderTag = ({ option, handleClose }) => {
    return h(
        NTag,
        {
            type: option.type as 'success' | 'warning' | 'error',
            closable: true,
            onMousedown: (e: FocusEvent) => {
                e.preventDefault()
            },
            onClose: (e: MouseEvent) => {
                e.stopPropagation()
                handleClose()
            }
        },
        { default: () => option.characterName }
    )
}

const keyWordPlanOptions = [
  {
    label : '场景推理-附加人物信息',
    value : 'V2',
  },
  {
     label : '场景推理-非Tag模式',
     value : 'V1',
  }
]

const nextStep =  (callback:any) =>{
  storyController.checkStoryBoardPrompt(props.storyId).then(res => {
    if(res.code === 200){
      callback(true)
    }else {
      message.error(res.data);
      callback(false)
    }
  })
}

defineExpose({
  nextStep
})

</script>
